package chapters19;

import java.util.concurrent.Semaphore;

/**
 * Created by xinxuchu on 2020/2/7.
 * 信号量Semaphore
 *
 * 经典应用场景：同时登陆网站人数限制
 */
public class AccessControlService {

    static class ConcurrentLimitException extends RuntimeException{

        private static final long serialVersionUID = 1L;

    }

    //todo 有机会得在公司的项目中尝试一下
    private static final int MAX_PERMITS = 100;
    private Semaphore permits = new Semaphore(MAX_PERMITS,true);
    public boolean login(String name,String password){
        if (!permits.tryAcquire()){
            //同时登陆用户数量超过限制
            throw new ConcurrentLimitException();
        }
        //.....其他验证
        return true;
    }

    public void login(){
        permits.release();
    }
}
